package cn.stylefeng.guns.sys.core.upay.response;

import cn.stylefeng.guns.sys.core.upay.exception.UpayException;
import cn.stylefeng.guns.sys.core.upay.utils.WebUtils;
import cn.stylefeng.guns.sys.core.util.common.StringUtils;
import com.alibaba.fastjson.JSON;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Map;

/**
 * @author zhou
 * @date 2019-7-30 09:53:49
 */
public class DefaultUmsClient implements UpayClient {
    private static final Logger logger = LoggerFactory.getLogger(DefaultUmsClient.class);

    @Override
    public UpayResponse execute(UpayRequest request, String md5Key, String url) throws UpayException {
        return execute(request, md5Key, null, url);
    }

    @Override
    public UpayResponse execute(UpayRequest request, String privateKey, String publicKey, String url) throws UpayException {
        try {
            Map<String, String> sendMessage = request.getSendData(privateKey);
            logger.info("发送服务器的数据=[{}]", sendMessage);
            String response = WebUtils.doPost(url, sendMessage, 3000, 60000);
            logger.info("收到后端返回的数据=[{}]", response);


            boolean isValidSign;

            // 说明是md5签名
            if (StringUtils.isEmpty(publicKey)) {
                isValidSign = UpayResponse.design(JSON.parseObject(response), privateKey);
            }
            else {
                isValidSign = UpayResponse.design(JSON.parseObject(response), publicKey);
            }

            if(!isValidSign) {
            	throw new UpayException("验签失败");
            }

            return JSON.parseObject(response, UpayResponse.class);

        } catch (IOException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new UpayException(e.getMessage());
        }
    }
}
